package oop.controller.action.user;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oop.controller.action.DefaultAction;
import oop.db.Database;

@SuppressWarnings("unused")
public class EditUserAction extends UserManagerAction {

	@Override
	public void perform()
			throws Exception {

		boolean userLogedIn = getUserInfo(request, response);
		if (userLogedIn) {
			if ("Change".equals(request.getParameter("change"))) {
				int errorEmail = updateEmail(request, response);
				int errorPass = updatePass(request, response);
				int error = 0;
				// if ((errorEmail == 0)&&(errorPass == 0));
				if (errorEmail == -1) {
					request.setAttribute("invalidEmail", "true");
					error++;
				} else if (errorEmail == -2) {
					request.setAttribute("emailUnavailable", "true");
					error++;
				} else if (errorEmail == -3) {
					request.setAttribute("dbError", "true");
					error++;
				}
				if ((errorPass == -1) || (errorPass == -3)) {
					request.setAttribute("wrongPass", "true");
					error++;
				} else if (errorPass == -2) {
					request.setAttribute("invalidPass", "true");
					error++;
				} else if (errorPass == -4) {
					request.setAttribute("dbError", "true");
					error++;
				}
				if (((errorEmail >= 0) && (errorPass >= 0))
						&& ((errorEmail != 0) || (errorPass != 0)))
					request.setAttribute("success", "true");
				if (error > 0)
					request.setAttribute("error", "true");
			}
		} else {
			setNextAction("user.login");
			return;
		}
	}

	public boolean getUserInfo(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			SQLException {
		String userName = (String) request.getSession(true).getAttribute(
				"username");

		if (userName == null)
			return false;
		Connection conn;
		try {
			conn = Database.get().getConnection();
			Statement stmt = conn.createStatement();
			String sql = "SELECT user_name, user_email, user_fullname "
					+ "FROM tblUser " + "WHERE user_name = '" + userName + "'";
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next()) {
				request.setAttribute("userCurrEmail", rs
						.getString("user_email"));
				request.setAttribute("userFullName", rs
						.getString("user_fullname"));
				return true;
			} else
				return false;

		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	private int updateEmail(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String email = request.getParameter("userEmail");
		if (isEmpty(email))
			return 0;
		if (isValidEmail(request, response) == false) {
			return -1;
		} else {
			if (isEmailExist(request, response)) {
				return -2;
			}
			Connection conn;
			try {
				conn = Database.get().getConnection();
				Statement stmt = conn.createStatement();
				String sql = "UPDATE `tracnghiem`.`tblUser` SET `user_email` = '"
						+ email
						+ "' WHERE `tblUser`.`user_name` ='"
						+ request.getSession().getAttribute("username") + "'";
				int result = stmt.executeUpdate(sql);
				return 1;
			} catch (SQLException e) {
				
				e.printStackTrace();
				return -3;
			}			
		}
	}

	private int updatePass(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String pass = request.getParameter("password");
		String changedPass = request.getParameter("changedPassword");
		String confirmPass = request.getParameter("confirmPass");
		String passOnSql = null;
		if ((isEmpty(pass)) && (isEmpty(changedPass)) && (isEmpty(confirmPass)))
			return 0;
		ResultSet rs = getUserPassOnSQL((String) request.getSession()
				.getAttribute("username"));
		try {
			if (rs.next()) {
				passOnSql = rs.getString("user_pass");
			} else
				return -3;
		} catch (SQLException e) {
			e.printStackTrace();
			return -3;
		}
		if (passOnSql == null)
			return -3;
		else if (pass.compareTo(passOnSql) != 0)
			return -1;
		else if (isValidPassword(request, response) == false)
			return -2;
		else {
			Connection conn;
			try {
				conn = Database.get().getConnection();
				Statement stmt = conn.createStatement();
				String sql = "UPDATE `tracnghiem`.`tblUser` SET `user_pass` = '"
						+ changedPass
						+ "' WHERE `tblUser`.`user_name` ='"
						+ request.getSession().getAttribute("username") + "'";
				int result = stmt.executeUpdate(sql);
				return 1;
			} catch (SQLException e) {
				
				e.printStackTrace();
				return -4;
			}	
		}

	}

	private boolean isValidPassword(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String pass = request.getParameter("changedPassword");
		String confPass = request.getParameter("confirmPass");
		if ((pass.compareTo(confPass) != 0) || (isEmpty(pass)))
			return false;
		return true;
	}
}
